/*
 * errorfunctions.c
 *
 *  Created on: Oct 3, 2013
 *      Author: cinus
 */

#include "errorfunctions.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>

float32 sumOfSquares(float32 *output, float32 *target, size_t size) {
	float32 delta;
	float32 Ep; //error of pattern
	size_t i;

	delta = .0f;
	Ep = .0f;
	for (i = 0; i < size; i++) {
		delta = target[i] - output[i];
		Ep += delta * delta;
	}
	Ep /= .5f;
	//fprintf(stderr, "Ep = %f\n", Ep);
	return Ep;
}

float32 meanSquaredError(float32 *output, float32 *target, size_t size) {
	float32 Ep; //error of pattern
	float32 mse;
	Ep = sumOfSquares(output, target, size);
	//fprintf(stderr, "Ep = %f\n", Ep);
	mse = Ep / (float32) size;
	//fprintf(stderr, "mse = %f\n", mse);
	return mse;
}
float32 crossEntropy(float32 *output, float32 *target, size_t size) {
	size_t i;
	float32 ce;

	ce = .0f;
	for (i = 0; i < size; i++) {
		if(target[i] > .0f){
			if(output[i] > .0f){
				ce -= target[i]*log(output[i]/target[i]);
			}else{
				ce -= log(FLT_MIN);
			}
		}

	}
	//fprintf(stderr, "log(FLT_MIN) = %f\n", log(FLT_MIN));
	/*if (isnan(penalty)) {
		fprintf(stderr, "log(%f) = %f\n", output[i], log(output[i]));
		fprintf(stderr, "%f * log(%f) = %f\n", target[i], output[i], target[i]*log(output[i]));
		fprintf(stderr, "%f * log(%f) + (1.0f - %f)*(1.0f*%f)", target[i], output[i], target[i], output[i]);
	}*/
	return ce;
}
